package com.qf.commons.web.aspect;

import com.qf.commons.base.result.Codes;
import com.qf.commons.web.aspect.utils.UserUtils;
import com.qf.commons.web.exception.ServiceException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * author Ken
 * create_time 2022/11/28
 */
@Aspect
@Component
public class AuthUserApsect {

    @Around("@annotation(com.qf.commons.web.aspect.annotation.GetUser)")
    public Object authUser(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取请求头？？？
        //获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String userJson = URLDecoder.decode(request.getHeader("userJson"), "UTF-8");
        //判断用户json是否为空
        if (userJson == null) {
            throw new ServiceException(Codes.AUTH_ERROR);
        }

        try {
            //直接放入到TheadLocal中
            UserUtils.setUser(userJson);
            //放行
            return joinPoint.proceed();
        } finally {
            //清除ThreadLocal
            UserUtils.clear();
        }
    }
}
